package com.hymjweb.demo.hymj.customer_manage.freight_agreement.air.service;

import com.alibaba.fastjson.JSONObject;
import com.hymjweb.demo.SpringAopUtil;
import com.hymjweb.demo.framework.cache.service.GlobalCacheService;
import com.hymjweb.demo.framework.result.MIniUIGridResultMap;
import com.hymjweb.demo.framework.sys.BaseService;
import com.hymjweb.demo.framework.sys.SysConstant;
import com.hymjweb.demo.framework.util.DataTypeUtil;
import com.hymjweb.demo.framework.util.DoubleUtil;
import com.hymjweb.demo.framework.util.ListSortUtil;
import com.hymjweb.demo.framework.util.util.PoiUtil;
import com.hymjweb.demo.hymj.basic_data_manage.xt_upload_file.bean.XtUploadFilePojo;
import com.hymjweb.demo.hymj.basic_data_manage.xt_upload_file.service.XtUploadFileService;
import com.hymjweb.demo.hymj.customer_manage.freight_agreement.bean.AgrementRatePojo;
import com.hymjweb.demo.hymj.customer_manage.freight_agreement.air.bean.BCustomerAirFreightAgreementPojo;
import com.hymjweb.demo.hymj.customer_manage.freight_agreement.air.mapper.BCustomerAirFreightAgreementMapper;
import com.hymjweb.demo.hymj.customer_manage.freight_agreement.detail.bean.BCustomerFeightAgreementDetailPojo;
import com.hymjweb.demo.hymj.customer_manage.freight_agreement.detail.service.BCustomerFeightAgreementDetailService;
import com.hymjweb.demo.hymj.customer_manage.freight_agreement.ticket_price.bean.BCustomerFreightTicketPricePojo;
import com.hymjweb.demo.hymj.customer_manage.freight_agreement.ticket_price.service.BCustomerFreightTicketPriceService;
import com.hymjweb.demo.hymj.log_manage.aop.annotation.OperationLogger;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.util.*;

@Service
public class BCustomerAirFreightAgreementService extends BaseService {

    @Autowired
    private BCustomerAirFreightAgreementMapper bCustomerAirFreightAgreementMapper;

    @Autowired
    private BCustomerFeightAgreementDetailService bCustomerFeightAgreementDetailService;

    @Autowired
    private BCustomerFreightTicketPriceService bCustomerFreightTicketPriceService;

    @Autowired
    private XtUploadFileService xtUploadFileService;

    @Autowired
    private GlobalCacheService globalCacheService;

    // key分隔符号
    private String keySeparate = " ";


    public List<BCustomerAirFreightAgreementPojo> getAllList(Map param) {
        return bCustomerAirFreightAgreementMapper.findAll(param);
    }

    public Object getPageList(Map param) {
        // 设置公共查询参数,加上部门
        this.setQueryCommParam(param);
        this.pageListInit(param);
        List list = getAllList(param);
        MIniUIGridResultMap resultMap = this.pageToGrid(list);
        return resultMap;
    }


    public BCustomerAirFreightAgreementPojo convertToJavaBean(JSONObject agreementPojo) {

        String opFlag = DataTypeUtil.toStringObject(agreementPojo.get("opFlag"));

        BCustomerAirFreightAgreementPojo pojo = agreementPojo.toJavaObject(BCustomerAirFreightAgreementPojo.class);

        Date currentTime = this.getSysTime();
        String czyId = this.getLoginCzyId();

        if (opFlag.equals(SysConstant.OPER_ADD)) {
            pojo.setId(this.getSysStrId());
            pojo.setCreateTime(currentTime);
            pojo.setCreateUserId(czyId);
        }

        pojo.setUpdateTime(currentTime);
        pojo.setUpdateUserId(czyId);

        // 明细与主表关联
        for (BCustomerFeightAgreementDetailPojo detailPojo : pojo.getDetailPojos()) {
            detailPojo.setId(this.getSysStrId());
            detailPojo.setAgreementFreightId(pojo.getId());
        }

        // 起票价与主表关联
        for (BCustomerFreightTicketPricePojo ticketPricePojo : pojo.getTicketPricePojos()) {
            ticketPricePojo.setId(this.getSysStrId());
            ticketPricePojo.setFreightAgreementId(pojo.getId());
        }

        return pojo;

    }

    public BCustomerAirFreightAgreementPojo getAirFreightAgreementPojo(BCustomerAirFreightAgreementPojo agreementPojo) {
        return bCustomerAirFreightAgreementMapper.getAirFreightAgreementPojo(agreementPojo);
    }

    @OperationLogger(oper = SysConstant.OPER_ADD, operTitle = "航空协议运价-添加", operMemo = "", classType = BCustomerAirFreightAgreementPojo.class)
    @Transactional(rollbackFor = {Exception.class})
    public int insert(BCustomerAirFreightAgreementPojo airAgreementPojo) throws Exception {

        if (airAgreementPojo == null) {
            throwException("协议动价对象为空，不能进行插入操作");
        }
        // 插入主表对象
        int effectRow = bCustomerAirFreightAgreementMapper.insert(airAgreementPojo);

        if (effectRow <= SysConstant.INT_ZERO) {
            return SysConstant.INT_ZERO;
        }

        // 获取明细对象
        List<BCustomerFeightAgreementDetailPojo> detailPojos = airAgreementPojo.getDetailPojos();
        if (detailPojos != null && detailPojos.size() > 0) {
            // 插入明细对象
            int detailEffectRow = bCustomerFeightAgreementDetailService.batchInsert(detailPojos);
            if (detailEffectRow <= SysConstant.INT_ZERO) {
                return SysConstant.INT_ZERO;
            }
        }

        // 插入起票价对象
        List<BCustomerFreightTicketPricePojo> ticketPricePojos = airAgreementPojo.getTicketPricePojos();
        if (ticketPricePojos != null && ticketPricePojos.size() > 0) {
            int ticketPriceAffectRows = bCustomerFreightTicketPriceService.batchInsert(ticketPricePojos);
            if (ticketPriceAffectRows <= SysConstant.INT_ZERO) {
                return SysConstant.INT_ZERO;
            }
        }

        return effectRow;
    }

    @Transactional(rollbackFor = {Exception.class})
    public int addAirFreightAgreement(BCustomerAirFreightAgreementPojo airAgreementPojo) throws Exception {
        // 2.根据 customerId airportId  cityId  airlinesId flightNo 组成UK,检索是否有重复
        BCustomerAirFreightAgreementPojo airAgreementPojo1 = getAirFreightAgreementPojo(airAgreementPojo);
        if (airAgreementPojo1 == null) {
            // 可以添加
            int airFreightAgreementPojoEffectRow = SpringAopUtil.getBean(this.getClass()).insert(airAgreementPojo);
            return airFreightAgreementPojoEffectRow;

        }
        return SysConstant.EXIST_STATUS.EXIST.getId();
    }


    @OperationLogger(oper = SysConstant.OPER_UPDATE, operTitle = "航空协议运价-更新", operMemo = "", classType = BCustomerAirFreightAgreementPojo.class)
    @Transactional(rollbackFor = {Exception.class})
    public int update(BCustomerAirFreightAgreementPojo airAgreementPojo) throws Exception {
        if(airAgreementPojo==null){
            throwException("航空协议运价更新参数错误!");
        }
        int effectRow = bCustomerAirFreightAgreementMapper.update(airAgreementPojo);
        return effectRow;
    }

    @Transactional(rollbackFor = {Exception.class})
    public int updateAirFreightAgreement(BCustomerAirFreightAgreementPojo airAgreementPojo) throws Exception {
        if(airAgreementPojo==null){
            throwException("航空协议运价更新参数错误!");
        }

        // 直接更新
        int affectRow = SpringAopUtil.getBean(this.getClass()).update(airAgreementPojo);

        if (affectRow <= SysConstant.INT_ZERO) {
            return SysConstant.INT_ZERO;
        }

        // 删除原来的detail列表，然后再重新批量插入
        int deleteAffectRow = bCustomerFeightAgreementDetailService.deleteByAgreementFreightId(airAgreementPojo.getId());
        List<BCustomerFeightAgreementDetailPojo> detailPojos = airAgreementPojo.getDetailPojos();
        if (detailPojos != null && detailPojos.size() > 0) {
            int detailAffectRow = bCustomerFeightAgreementDetailService.batchInsert(detailPojos);
            if (detailAffectRow <= SysConstant.INT_ZERO) {
                return SysConstant.INT_ZERO;
            }
        }

        // 删除原来的起票价
        int deleteTickePriceAffectRow = bCustomerFreightTicketPriceService.deleteByAgreementFreightId(airAgreementPojo.getId());
        List<BCustomerFreightTicketPricePojo> ticketPricePojos = airAgreementPojo.getTicketPricePojos();
        if (ticketPricePojos != null && ticketPricePojos.size() > 0) {
            int ticketPriceAffectRow = bCustomerFreightTicketPriceService.batchInsert(ticketPricePojos);
            if (ticketPriceAffectRow <= SysConstant.INT_ZERO) {
                return SysConstant.INT_ZERO;
            }
        }

        return affectRow;
    }

    @OperationLogger(oper = SysConstant.OPER_UPDATE, operTitle = "航空协议运价-删除", operMemo = "", classType = BCustomerAirFreightAgreementPojo.class)
    @Transactional(rollbackFor = {Exception.class})
    public int delete(String agreementFreightIds) throws Exception {
        if(DataTypeUtil.isEmptyStr(agreementFreightIds)){
            throwException("航空协议运价删除参数错误!");
        }

        // 1.批量获取客户运价主表对象
        List<BCustomerAirFreightAgreementPojo> airPojos = bCustomerAirFreightAgreementMapper.getAirFreightAgreementPojoByIds(agreementFreightIds);
        // 2.遍历一下，获取所有文件对象IDS
        List<String> fileIds = new ArrayList<>();
        for (BCustomerAirFreightAgreementPojo pojo : airPojos) {
            if (pojo.getFileId() != null) {
                fileIds.add(pojo.getFileId());
            }
        }

        // 3.批量删除detail表中的数据
        int detailDeleteEffectRows = bCustomerFeightAgreementDetailService.batchDeleteByAgreementFreightIds(agreementFreightIds);

        if (detailDeleteEffectRows >= SysConstant.INT_ZERO) {
            // 4.删除起票价
            int ticketPriceAffectRows = bCustomerFreightTicketPriceService.batchDeleteTicketPriceByAgreementFreightIds(agreementFreightIds);

            if (ticketPriceAffectRows >= SysConstant.INT_ZERO) {
                // 5.删除主表对象对应的文件
                if (fileIds.size() > 0) {
                    xtUploadFileService.deleteFile(fileIds);
                }

                // 6.删除主表对象
                int effectRows = bCustomerAirFreightAgreementMapper.deleteByIds(agreementFreightIds);
                if (effectRows >= SysConstant.INT_ZERO) {
                    return effectRows;
                }
            }
        }

        return SysConstant.INT_ZERO;
    }

    /**
     * 上传并导入文件
     *
     * @param upLoadFile
     * @return
     * @throws Exception
     */
    public int upload(MultipartFile upLoadFile) throws Exception {
        if(upLoadFile==null){
            throwException("导入航空协议运价参数错误!");
        }
        // 上传Excel文件
        XtUploadFilePojo filePojo = xtUploadFileService.upload(upLoadFile);

        // Excel内容转成对象
        List<BCustomerAirFreightAgreementPojo> airFreightAgreementPojos = convertExcelToFreightAgreementList(filePojo);

        if (airFreightAgreementPojos.isEmpty()) {
            throwException("Excel文件内容为空，不能导入协议运价!");
        }

        // 插入对象到数据库
        int affectRows = airFreightAgreementPojosToDb(airFreightAgreementPojos);

        // 返回插入受影响的协议运价主表的行数
        return affectRows;
    }

    /**
     * 协议运价列表入库
     *
     * @param airFreightAgreementPojos
     * @return
     */
    @Transactional(rollbackFor = {Exception.class})
    public int airFreightAgreementPojosToDb(List<BCustomerAirFreightAgreementPojo> airFreightAgreementPojos) throws Exception {

        if(airFreightAgreementPojos==null || airFreightAgreementPojos.isEmpty()){
            throwException("待导入协议运价列表为空，导入协议运价失败!");
        }

        // 起票价列表
        List<BCustomerFreightTicketPricePojo> ticketPricePojos = new ArrayList<>();
        // 明细列表
        List<BCustomerFeightAgreementDetailPojo> agreementDetailPojos = new ArrayList<>();

        String agreementIds = "";
        for (BCustomerAirFreightAgreementPojo pojo : airFreightAgreementPojos) {
            ticketPricePojos.addAll(pojo.getTicketPricePojos());
            agreementDetailPojos.addAll(pojo.getDetailPojos());

            // 根据pojo的UK获取已经存在对象，然后直接删除
            BCustomerAirFreightAgreementPojo dbPojo = queryPojoByUk(pojo);
            if (dbPojo != null) {
                String agreementPojoId = dbPojo.getId();
                // 构建删除主表的IDS
                agreementIds += "'" + agreementPojoId + "',";

            }
        }
        // 去除最后面的逗号
        if (agreementIds.length() > 0) {
            agreementIds = agreementIds.substring(0, agreementIds.length() - 1);

            // 删除主表对象同时，也会删除子表对象，同时还会清空原来的文件
            int deleteRows = SpringAopUtil.getBean(this.getClass()).delete(agreementIds);
        }

        // 1.主表对象入库批量入库
        int agreementAffectRows = batchInsert(airFreightAgreementPojos);
        if (agreementAffectRows <= SysConstant.INT_ZERO) {
            throwException("协议运价数据导入失败，请重试!");
        }

        // 2.协议运价明细批量入库
        int agreementDetailAffectRows = bCustomerFeightAgreementDetailService.batchInsert(agreementDetailPojos);
        if (agreementDetailAffectRows <= SysConstant.INT_ZERO) {
            throwException("协议运价明细添加失败，请重试!");
        }

        // 3.起票价批量入库
        int ticketPriceAffectRows = bCustomerFreightTicketPriceService.batchInsert(ticketPricePojos);
        if (ticketPriceAffectRows <= SysConstant.INT_ZERO) {
            throwException("起票价添加失败，请重试!");
        }

        return agreementAffectRows;
    }


    /**
     * 根据UK锁定主表对象
     *
     * @param pojo
     * @return
     */
    public BCustomerAirFreightAgreementPojo queryPojoByUk(BCustomerAirFreightAgreementPojo pojo) {
        return bCustomerAirFreightAgreementMapper.getAirFreightAgreementPojo(pojo);
    }


    /**
     * 空动协议运价对象批量插入
     *
     * @param airFreightAgreementPojos
     * @return
     */
    @Transactional(rollbackFor = {Exception.class})
    public int batchInsert(List<BCustomerAirFreightAgreementPojo> airFreightAgreementPojos) throws Exception {
        if (airFreightAgreementPojos == null || airFreightAgreementPojos.isEmpty()) {
            throwException("空动协议运价列表对象为空，添加失败，请重试!");
        }
        return bCustomerAirFreightAgreementMapper.batchInsert(airFreightAgreementPojos);
    }


    /**
     * 协议运价excel数据转对象
     *
     * @param filePojo
     * @return
     * @throws Exception
     */
    public List<BCustomerAirFreightAgreementPojo> convertExcelToFreightAgreementList(XtUploadFilePojo filePojo) throws Exception {

        if(filePojo==null){
            throwException("待导入对象不存在!");
        }

        File destFile = xtUploadFileService.getFile(filePojo);


        // 定义读取文件的输入流
        FileInputStream fis = new FileInputStream(destFile);

        Workbook wb = PoiUtil.getWorkBook(destFile, fis);

        Object[][] agreementTableArray = PoiUtil.getExcelRowsValue(wb, 0);

        // 1.定义一个客户Map
        Map<String, String> customerMap = new HashMap<>();

        // 2.定义始发机场Map
        Map<String, String> airportMap = new HashMap<>();

        // 3.目的站Map
        Map<String, String> cityMap = new HashMap<>();

        // 4.航空公司Map
        Map<String, String> airlinesMap = new HashMap<>();

        // 5.运价标准
        Map<String, String> standardMap = new HashMap<>();

        // 6.货物类型
        Map<String, String> goodsTypeMap = new HashMap<>();

        // 8.存储行key与行数的对应关系 key = 客户,始发机场,目的站,航空公司,航班号,运价标准类型,货物类型
        Map<String, List<Object[]>> rowKeyCacheData = new HashMap<>();
        Set<String> rowKeySet = new HashSet<>();

        // 存储异常信息
        StringBuffer exceptionBufferStr = new StringBuffer("");

        // 缓存初始化
        for (int rowIndex = 1; rowIndex < agreementTableArray.length; rowIndex++) {
            // 获取指定行
            Object[] rowDataArray = agreementTableArray[rowIndex];

            // 读取客户名称，翻译后缓存
            loadBaseCache(rowDataArray, rowIndex, 1, exceptionBufferStr, DataTypeUtil.toNotNullString(agreementTableArray[0][1]), SysConstant.CACHE_M_CUSTOMER, customerMap);

            // 读取始发机场，翻译后缓存
            loadBaseCache(rowDataArray, rowIndex, 2, exceptionBufferStr, DataTypeUtil.toNotNullString(agreementTableArray[0][2]), SysConstant.CACHE_XT_AIRPORT, airportMap);

            // 读取目的站，翻译后缓存
            loadBaseCache(rowDataArray, rowIndex, 3, exceptionBufferStr, DataTypeUtil.toNotNullString(agreementTableArray[0][3]), SysConstant.CACHE_XT_CITY, cityMap);

            // 读取航空公司，翻译后缓存
            loadBaseCache(rowDataArray, rowIndex, 4, exceptionBufferStr, DataTypeUtil.toNotNullString(agreementTableArray[0][4]), SysConstant.CACHE_XT_AIRLINES, airlinesMap);

            // 读取运价标准，翻译后缓存
            loadBaseCache(rowDataArray, rowIndex, 6, exceptionBufferStr, DataTypeUtil.toNotNullString(agreementTableArray[0][6]), SysConstant.CACHE_XT_DIC, standardMap);

            // 读取货物类型，翻译后缓存
            loadBaseCache(rowDataArray, rowIndex, 7, exceptionBufferStr, DataTypeUtil.toNotNullString(agreementTableArray[0][7]), SysConstant.CACHE_XT_DIC, goodsTypeMap);

            String flightNoName = DataTypeUtil.toStringObject(agreementTableArray[5]);
            if (flightNoName == null) {
                exceptionBufferStr.append("导入数据的【" + rowIndex + "】行【" + DataTypeUtil.toNotNullString(agreementTableArray[0][5]) + "】列有空白，不能导入数据!<br/>");
            } else {
                // 构建key
                String rowKey = generateRowKey(rowDataArray);
                rowKeySet.add(rowKey);
            }

            // 数据校验
            // 起票价
            Double ticetPrice = DataTypeUtil.toDouble(agreementTableArray[rowIndex][8], -1);
            if (ticetPrice == -1) {
                exceptionBufferStr.append("导入数据的【" + rowIndex + "】行【" + DataTypeUtil.toNotNullString(agreementTableArray[0][8]) + "】列有空白或不是整数值类型，不能导入数据!<br/>");
            }
            Integer startValue = DataTypeUtil.toInt(agreementTableArray[rowIndex][9], -1);
            if (startValue == -1) {
                exceptionBufferStr.append("导入数据的【" + rowIndex + "】行【" + DataTypeUtil.toNotNullString(agreementTableArray[0][9]) + "】列有空白或不是整数值类型，不能导入数据!<br/>");
            }
            Integer endValue = DataTypeUtil.toInt(agreementTableArray[rowIndex][10], -1);
            if (endValue == -1) {
                exceptionBufferStr.append("导入数据的【" + rowIndex + "】行【" + DataTypeUtil.toNotNullString(agreementTableArray[0][10]) + "】列有空白或不是整数值类型，不能导入数据!<br/>");
            }
            Double price = DataTypeUtil.toDouble(agreementTableArray[rowIndex][11], -1);
            if (price == -1) {
                exceptionBufferStr.append("导入数据的【" + rowIndex + "】行【" + DataTypeUtil.toNotNullString(agreementTableArray[0][11]) + "】列有空白或不是整数值类型，不能导入数据!<br/>");
            }
            String scope = DataTypeUtil.toStringObject(agreementTableArray[rowIndex][12]);
            if (scope == null) {
                exceptionBufferStr.append("导入数据的【" + rowIndex + "】行【" + DataTypeUtil.toNotNullString(agreementTableArray[0][12]) + "】列有空白，不能导入数据!<br/>");
            }
            // 第13列不读取
        }

        // 有异常信息，直接向抛出异常后返回
        if (exceptionBufferStr.length() > 0) {
            throwException(exceptionBufferStr.toString());
        }

        // 获取创建人与创建时间
        String czyId = this.getLoginCzyId();
        Date currentDate = this.getSysTime();


        List<BCustomerAirFreightAgreementPojo> freightAgreementPojoList = new ArrayList<>();

        for (String rowCacheKey : rowKeySet) {

            // 可以构建协议运价主表对象
            String[] keyArray = rowCacheKey.split(keySeparate);
            //  客户 始发机场 目的站 航空公司 航班号
            String customerId = customerMap.get(keyArray[0]);
            String airportId = airportMap.get(keyArray[1]);
            String cityId = cityMap.get(keyArray[2]);
            String airlinesId = airlinesMap.get(keyArray[3]);
            String flightNo = keyArray[4];

            // 创建主表对象
            BCustomerAirFreightAgreementPojo bCustomerAirFreightAgreementPojo = new BCustomerAirFreightAgreementPojo();
            bCustomerAirFreightAgreementPojo.setId(this.getSysStrId());
            bCustomerAirFreightAgreementPojo.setCustomerId(customerId);
            bCustomerAirFreightAgreementPojo.setAirportId(airportId);
            bCustomerAirFreightAgreementPojo.setAirlinesId(airlinesId);
            bCustomerAirFreightAgreementPojo.setCityId(cityId);
            bCustomerAirFreightAgreementPojo.setFlightNo(flightNo);
            // 设置上传文件ID
            bCustomerAirFreightAgreementPojo.setFileId(filePojo.getId());
            // 备注没有设置也不需要设置
            bCustomerAirFreightAgreementPojo.setCreateUserId(czyId);
            bCustomerAirFreightAgreementPojo.setCreateTime(currentDate);
            bCustomerAirFreightAgreementPojo.setUpdateUserId(czyId);
            bCustomerAirFreightAgreementPojo.setUpdateTime(currentDate);

            bCustomerAirFreightAgreementPojo.setTicketPricePojos(new ArrayList<>());
            bCustomerAirFreightAgreementPojo.setDetailPojos(new ArrayList<>());


            // 构建主表所有数据列表
            List<Object[]> rowCacheKeyData = new ArrayList<>();

            for (int rowIndex = 1; rowIndex < agreementTableArray.length; rowIndex++) {
                // 获取指定行
                Object[] rowDataArray = agreementTableArray[rowIndex];
                String rowKey = generateRowKey(rowDataArray);
                if (rowKey.equals(rowCacheKey)) {
                    rowCacheKeyData.add(rowDataArray);
                }
            }


            // 创建起票价Map集合，用于生成起票价列表
            Map<String, Double> ticketPriceMap = new HashMap<>();
            // 根据rowCacheKeyData构建明细对象与起票对象
            for (Object[] rowObj : rowCacheKeyData) {
                Double ticketPriceValue = DataTypeUtil.toDouble(rowObj[8]);
                String ticketPriceKey = generateTicketPriceKey(rowObj);
                Double mapTicketPrice = ticketPriceMap.get(ticketPriceKey);
                if (mapTicketPrice == null) {
                    ticketPriceMap.put(ticketPriceKey, ticketPriceValue);
                } else if (!mapTicketPrice.equals(ticketPriceValue)) {
                    exceptionBufferStr.append("导入数据的【" + keyArray[0] + "】客户的相同航班、重量或体积运价标准、货物类型的起票价有不相同的值，不能导入数据!<br/>");
                }
            }

            // 检测不合格直接抛异常结束
            if (exceptionBufferStr.length() > 0) {
                throwException(exceptionBufferStr.toString());
            }

            // 构建起票价列表对象
            List<BCustomerFreightTicketPricePojo> ticketPricePojoList = new ArrayList<>();
            // 到些可以直接构建对应的起票价对象
            for (Map.Entry<String, Double> entry : ticketPriceMap.entrySet()) {
                String ticketPriceKey = entry.getKey();
                Double ticketPriceValue = entry.getValue();
                String[] ticketPriceKeyArray = ticketPriceKey.split(" ");
                Long stardandId = DataTypeUtil.toLong(standardMap.get(ticketPriceKeyArray[0]));
                Long goodsTypeId = DataTypeUtil.toLong(goodsTypeMap.get(ticketPriceKeyArray[1]));
                // 创建起票对象
                BCustomerFreightTicketPricePojo bCustomerFreightTicketPricePojo = new BCustomerFreightTicketPricePojo();
                bCustomerFreightTicketPricePojo.setId(this.getSysStrId());
                // 设置起票对象关联的协议对象
                bCustomerFreightTicketPricePojo.setFreightAgreementId(bCustomerAirFreightAgreementPojo.getId());
                bCustomerFreightTicketPricePojo.setStandardTypeId(stardandId);
                bCustomerFreightTicketPricePojo.setGoodsTypeId(goodsTypeId);
                bCustomerFreightTicketPricePojo.setTicketPrice(ticketPriceValue);

                ticketPricePojoList.add(bCustomerFreightTicketPricePojo);
            }
            // 将主表的起票价加入一到主表对象的集合中
            bCustomerAirFreightAgreementPojo.getTicketPricePojos().addAll(ticketPricePojoList);

            // 下面处理协议运价明细
            for (Object[] rowObj : rowCacheKeyData) {

                String key = generateTicketPriceKey(rowObj);
                // 创建主表明细列表对象
                List<BCustomerFeightAgreementDetailPojo> detailPojoList = new ArrayList<>();
                // 遍历之前生成的起票价map
                for (Map.Entry<String, Double> entry : ticketPriceMap.entrySet()) {
                    String ticketPriceKey = entry.getKey();
                    String[] ticketPriceKeyArray = ticketPriceKey.split(keySeparate);
                    Long stardandId = DataTypeUtil.toLong(standardMap.get(ticketPriceKeyArray[0]));
                    Long goodsTypeId = DataTypeUtil.toLong(goodsTypeMap.get(ticketPriceKeyArray[1]));

                    if (key.equals(ticketPriceKey)) {
                        Integer startValue = DataTypeUtil.toInteger(rowObj[9]);
                        Integer endValue = DataTypeUtil.toInteger(rowObj[10]);
                        Double price = DataTypeUtil.toDouble(rowObj[11]);
                        String scopeComment = DataTypeUtil.toStringObject(rowObj[12]);
                        // 可以创建deatil对象
                        BCustomerFeightAgreementDetailPojo bCustomerFeightAgreementDetailPojo = new BCustomerFeightAgreementDetailPojo();
                        bCustomerFeightAgreementDetailPojo.setId(this.getSysStrId());
                        bCustomerFeightAgreementDetailPojo.setAgreementFreightTypeId(SysConstant.XT_DIC_TRANSPORT_SPECIES.AIR.getId());
                        // 关联主表ID
                        bCustomerFeightAgreementDetailPojo.setAgreementFreightId(bCustomerAirFreightAgreementPojo.getId());
                        bCustomerFeightAgreementDetailPojo.setStandardTypeId(stardandId);
                        bCustomerFeightAgreementDetailPojo.setGoodsTypeId(goodsTypeId);
                        bCustomerFeightAgreementDetailPojo.setStartValue(startValue);
                        bCustomerFeightAgreementDetailPojo.setEndValue(endValue);
                        bCustomerFeightAgreementDetailPojo.setPrice(price);
                        bCustomerFeightAgreementDetailPojo.setComment(scopeComment);

                        detailPojoList.add(bCustomerFeightAgreementDetailPojo);
                    }
                }

                if (detailPojoList.size() > 0) {
                    // 加入的对象按起始值排序
                    ListSortUtil.sort(detailPojoList, new String[]{"agreementFreightId", "standardTypeId"}, new boolean[]{true, true});
                    //Collections.sort(detailPojoList);

                    // 下面进行值的检验
                    for (int i = 0; i < detailPojoList.size() - 1; i++) {
                        Integer value1 = detailPojoList.get(i).getEndValue();
                        Integer value2 = detailPojoList.get(i + 1).getStartValue();
                        if (!value1.equals(value2)) {
                            exceptionBufferStr.append("【" + keyArray[0] + "】客户的协议运价范围在设置时有不连续范围出现!<br/>");
                        }
                    }

                    if (exceptionBufferStr.length() > 0) {
                        throwException(exceptionBufferStr.toString());
                    }

                    bCustomerAirFreightAgreementPojo.getDetailPojos().addAll(detailPojoList);
                }

            }

            // 一定要把主表对象加入集合
            freightAgreementPojoList.add(bCustomerAirFreightAgreementPojo);
        }

        return freightAgreementPojoList;

    }


    /**
     * 生成起票价key
     *
     * @param rowDataArray
     * @return
     */
    private String generateTicketPriceKey(Object[] rowDataArray) {
        return DataTypeUtil.toStringObject(rowDataArray[6]) + keySeparate + DataTypeUtil.toStringObject(rowDataArray[7]);
    }

    /**
     * 生成行key = 客户 始发机场 目的站 航空公司 航班号
     *
     * @param rowDataArray
     * @return
     */
    private String generateRowKey(Object[] rowDataArray) {
        StringBuffer keyBuffer = new StringBuffer("");
        for (int i = 1; i < 6; i++) {
            keyBuffer.append(DataTypeUtil.toStringObject(rowDataArray[i]).trim() + keySeparate);
        }
        return keyBuffer.toString().trim();
    }


    /**
     * 加载基础Cache,用于后面的翻译转换
     *
     * @param rowDataArray
     * @param rowIndex
     * @param colIndex
     * @param exceptionBufferStr
     * @param colName
     * @param cacheName
     * @param cacheMap
     */
    private void loadBaseCache(Object[] rowDataArray, int rowIndex, int colIndex, StringBuffer exceptionBufferStr, String colName, String cacheName, Map<String, String> cacheMap) {
        // 读取目的站，翻译后缓存
        String valueName = DataTypeUtil.toStringObject(rowDataArray[colIndex]).trim();
        if (valueName == null) {
            exceptionBufferStr.append("导入数据的【" + rowIndex + "】行【" + colName + "】列有空白，不能导入数据!<br/>");
        } else {
            // 1.从缓存中判断一下
            if (!cacheMap.containsKey(valueName)) {
                String valueId = globalCacheService.getIdByCacheNameAndName(cacheName, valueName);
                if (valueId == null) {
                    exceptionBufferStr.append("导入数据的" + colName + "【" + valueName + "】，在系统中不存在，不能导入数据!<br/>");
                } else {
                    cacheMap.put(valueName, valueId);
                }
            }
        }
    }


    @Deprecated
    @Transactional(rollbackFor = {Exception.class})
    public int excelToDatabase(XtUploadFilePojo filePojo) throws Exception {

        File destFile = xtUploadFileService.getFile(filePojo);

        // 定义读取文件的输入流
        FileInputStream fis = new FileInputStream(destFile);
        ;

        Workbook wb = PoiUtil.getWorkBook(destFile, fis);

        Sheet sheet = wb.getSheetAt(0);

        int rows = sheet.getLastRowNum();

        if (rows < 2) {
            throwException("Excel文件内容为空");
        }

        // 1.按行读取所有Excel中的每一行，形成一个List<Map>
        List<Map<String, Object>> listMap = new ArrayList<>();

        // 异常处理字符串
        StringBuffer exceptionInfoStr = new StringBuffer();

        // 检测是否有UK重复
        Set<String> airCheckObjSet = new HashSet<>();

        for (int i = 1; i <= rows; i++) {
            Map<String, Object> map = new HashMap<>();
            Row row = sheet.getRow(i);
            int rowNum = row.getRowNum() + 1;
            if (row != null) {
                // 序号(0)	客户(1)	始发机场(2)	目的站(3)	航空公司(4)	航班号(5)	运价标准类型(6)	货物类型(7)	起始值(8)	结束值(9)	单价(10)	范围说明(11)	备注(12)
                // 客户名称
                String customerName = PoiUtil.getExcelCellValue(wb, row, 1);
                if (DataTypeUtil.isEmptyStr(customerName)) {
                    exceptionInfoStr.append("上传的excel文件中的【" + rowNum + "】行【客户】为空<br/>");
                }

                map.put("customerName", customerName);

                // 始发机场
                String airportName = PoiUtil.getExcelCellValue(wb, row, 2);
                if (DataTypeUtil.isEmptyStr(airportName)) {
                    exceptionInfoStr.append("上传的excel文件中的【" + rowNum + "】行【始发机场】为空<br/>");
                }
                map.put("airportName", airportName);

                // 目的站
                String cityName = PoiUtil.getExcelCellValue(wb, row, 3);
                if (DataTypeUtil.isEmptyStr(cityName)) {
                    exceptionInfoStr.append("上传的excel文件中的【" + rowNum + "】行【目的站】为空<br/>");
                }
                map.put("cityName", cityName);

                // 航空公司
                String airlinesName = PoiUtil.getExcelCellValue(wb, row, 4);
                if (DataTypeUtil.isEmptyStr(airlinesName)) {
                    exceptionInfoStr.append("上传的excel文件中的【" + rowNum + "】行【航空公司】为空<br/>");
                }
                map.put("airlinesName", airlinesName);

                // 航班号
                String flightNo = PoiUtil.getExcelCellValue(wb, row, 5);
                if (DataTypeUtil.isEmptyStr(flightNo)) {
                    exceptionInfoStr.append("上传的excel文件中的【" + rowNum + "】行【航班号】为空<br/>");
                }
                map.put("flightNo", flightNo);

                //客户协议运价标准分类standardTypeId
                String standardTypeName = PoiUtil.getExcelCellValue(wb, row, 6);
                if (DataTypeUtil.isEmptyStr(standardTypeName)) {
                    exceptionInfoStr.append("上传的excel文件中的【" + rowNum + "】行【运价标准类型】为空<br/>");
                }
                map.put("standardTypeName", standardTypeName);

                //货物类型goodsTypeId
                String goodsTypeName = PoiUtil.getExcelCellValue(wb, row, 7);
                if (DataTypeUtil.isEmptyStr(goodsTypeName)) {
                    exceptionInfoStr.append("上传的excel文件中的【" + rowNum + "】行【货物类型】为空<br/>");
                }
                map.put("goodsTypeName", goodsTypeName);

                //起始值
                Integer startValue = DataTypeUtil.toInteger(PoiUtil.getExcelCellValue(wb, row, 8));
                if (DataTypeUtil.isEmptyStr(startValue)) {
                    exceptionInfoStr.append("上传的excel文件中的【" + rowNum + "】行【起始值】为空<br/>");
                }
                map.put("startValue", startValue);

                //结束值
                Integer endValue = DataTypeUtil.toInteger(PoiUtil.getExcelCellValue(wb, row, 9));
                if (DataTypeUtil.isEmptyStr(endValue)) {
                    exceptionInfoStr.append("上传的excel文件中的【" + rowNum + "】行【结束值】为空<br/>");
                }
                map.put("endValue", endValue);

                //单价
                Double price = DataTypeUtil.toDouble(PoiUtil.getExcelCellValue(wb, row, 10));
                if (DataTypeUtil.isEmptyStr(price)) {
                    exceptionInfoStr.append("上传的excel文件中的【" + rowNum + "】行【单价】为空<br/>");
                }
                map.put("price", price);

                String standardComment = PoiUtil.getExcelCellValue(wb, row, 11);
                String comment = PoiUtil.getExcelCellValue(wb, row, 12);

                map.put("standardComment", standardComment);
                map.put("comment", comment);

                airCheckObjSet.add(customerName + airportName + cityName + airlinesName + flightNo);

                listMap.add(map);
            }
        }

        if (exceptionInfoStr.length() > 0) {
            deleteFile(filePojo);
            throwException(exceptionInfoStr.toString());
        }

        // 2.校验所有List中的Map的相应字段值是否一样,构成的一个Key
        // 客户	始发机场	目的站	航空公司	航班号
        if (airCheckObjSet.size() > 1) {
            deleteFile(filePojo);
            throwException("导入的数据【客户】【始发机场】【目的站】【航空公司】【航班号】【起票价】列有不同的值，不能导入！");
        }

        /**
         * id
         * customer_id
         * airport_id
         * city_id
         * airlines_id
         * flight_no
         * file_id
         * comment
         */

        Map<String, Object> mapObj = listMap.get(0);
        // 客户customerName
        String customerId = globalCacheService.getIdByCacheNameAndName(SysConstant.CACHE_M_CUSTOMER, mapObj.get("customerName").toString());
        if (customerId == null) {
            exceptionInfoStr.append("上传的excel文件中的【客户:" + mapObj.get("customerName").toString() + "】 在客户列表中找不到对应ID<br/>");
        }

        // 始发机场airportId
        String airportId = globalCacheService.getIdByCacheNameAndName(SysConstant.CACHE_XT_AIRPORT, mapObj.get("airportName").toString());
        if (customerId == null) {
            exceptionInfoStr.append("上传的excel文件中的【始发机场:" + mapObj.get("airportName").toString() + "】在机场表中找不到对应ID<br/>");
        }

        //目的站
        String cityId = globalCacheService.getIdByCacheNameAndName(SysConstant.CACHE_XT_CITY, mapObj.get("cityName").toString());
        if (cityId == null) {
            exceptionInfoStr.append("上传的excel文件中的【目的站:" + mapObj.get("cityName").toString() + "】在系统区域表中找不到对应ID<br/>");
        }

        // 航空公司
        String airlinesId = globalCacheService.getIdByCacheNameAndName(SysConstant.CACHE_XT_AIRLINES, mapObj.get("airlinesName").toString());
        if (airlinesId == null) {
            exceptionInfoStr.append("上传的excel文件中的【航空公司:" + mapObj.get("airlinesName").toString() + "】在航空公司表中找不到对应ID<br/>");
        }

        if (exceptionInfoStr.length() > 0) {
            deleteFile(filePojo);
            throwException(exceptionInfoStr.toString());
        }

        Date currentTime = this.getSysTime();
        String czyId = this.getLoginCzyId();
        // 生成主表对象
        BCustomerAirFreightAgreementPojo airPojo = new BCustomerAirFreightAgreementPojo();
        airPojo.setCustomerId(customerId);
        airPojo.setAirportId(airportId);
        airPojo.setCityId(cityId);
        airPojo.setAirlinesId(airlinesId);
        airPojo.setFlightNo(mapObj.get("flightNo").toString());
        airPojo.setFileId(filePojo.getId());// 要写入文件数据库
        airPojo.setComment(mapObj.get("comment").toString());
        airPojo.setCreateTime(currentTime);
        airPojo.setCreateUserId(czyId);
        airPojo.setUpdateTime(currentTime);
        airPojo.setUpdateUserId(czyId);
        airPojo.setDetailPojos(new ArrayList<>());

        String opType = SysConstant.OPER_ADD; // 这个代表插入
        // 检测airPojo 否存在,如果存在就删除其明细，同时列新airPojo对象，注意这个地方可能要更换ID,
        BCustomerAirFreightAgreementPojo newAirPojo = getAirFreightAgreementPojo(airPojo);
        if (newAirPojo != null) {
            airPojo.setId(newAirPojo.getId());
            opType = SysConstant.OPER_UPDATE;
        } else {
            airPojo.setId(this.getSysStrId());
        }

        // 定义四个detail对象集合
        List<BCustomerFeightAgreementDetailPojo> weightGeneralDetailList = new ArrayList<>();// 重量 普货
        List<BCustomerFeightAgreementDetailPojo> weightFreshDetailList = new ArrayList<>();  // 重量 鲜活
        List<BCustomerFeightAgreementDetailPojo> volumeGeneralDetailList = new ArrayList<>(); // 体积 普货
        List<BCustomerFeightAgreementDetailPojo> volumeFreshDetailList = new ArrayList<>();  // 体积 鲜活

        // 迭代生成detail对象
        for (int i = 0; i < listMap.size(); i++) {
            Map<String, Object> objMap = listMap.get(i);
            String standardTypeName = objMap.get("standardTypeName").toString();
            String goodsTypeName = objMap.get("goodsTypeName").toString();
            //客户协议运价标准分类standardTypeId
            Long standardTypeId = DataTypeUtil.toLongObject(globalCacheService.getIdByCacheNameAndName(SysConstant.CACHE_XT_DIC, standardTypeName));
            if (standardTypeId == null) {
                exceptionInfoStr.append("上传的excel文件中的【运价标准类型:" + standardTypeName + "】在字典表中找不到对应ID<br/>");
            }

            //货物类型goodsTypeId
            Long goodsTypeId = DataTypeUtil.toLongObject(globalCacheService.getIdByCacheNameAndName(SysConstant.CACHE_XT_DIC, goodsTypeName));
            if (goodsTypeId == null) {
                exceptionInfoStr.append("上传的excel文件中的【货物类型:" + goodsTypeName + "】在字典表中找不到对应ID<br/>");
            }

            // 起始值	结束值	单价	范围说明
            Integer startValue = DataTypeUtil.toInteger(objMap.get("startValue"));
            Integer endValue = DataTypeUtil.toInteger(objMap.get("endValue"));
            Double price = DataTypeUtil.toDouble(objMap.get("price"));
            String comment = DataTypeUtil.toStringObject(objMap.get("standardComment"));

            if (DataTypeUtil.isEmptyStr(startValue) || startValue < 0) {
                exceptionInfoStr.append("上传的excel文件中的【起始值】列有非整数值或值小于零<br/>");
            }
            if (DataTypeUtil.isEmptyStr(endValue) || startValue < 0) {
                exceptionInfoStr.append("上传的excel文件中的【结束值】列有非整数值或值小于零<br/>");
            }
            if (DataTypeUtil.isEmptyStr(price) || startValue < 0) {
                exceptionInfoStr.append("上传的excel文件中的【单价】列有非数值或值小于零<br/>");
            }

            // 可以生成对象
            BCustomerFeightAgreementDetailPojo detailPojo = new BCustomerFeightAgreementDetailPojo();
            detailPojo.setId(this.getSysStrId());
            detailPojo.setAgreementFreightTypeId(SysConstant.XT_DIC_TRANSPORT_SPECIES.AIR.getId());
            detailPojo.setAgreementFreightId(airPojo.getId());
            detailPojo.setStandardTypeId(standardTypeId);
            detailPojo.setGoodsTypeId(goodsTypeId);
            detailPojo.setStartValue(startValue);
            detailPojo.setEndValue(endValue);
            detailPojo.setPrice(price);
            detailPojo.setComment(comment);

            if (standardTypeId.longValue() == SysConstant.XT_DIC_CUSTOMER_AGREEMENT_FREIGHT_STANDARD.weight.getId()) {
                if (goodsTypeId.longValue() == SysConstant.XT_DIC_GOODS_TYPE.GENERAL_CARGO.getId()) {
                    weightGeneralDetailList.add(detailPojo);
                } else {
                    weightFreshDetailList.add(detailPojo);
                }
            } else {
                if (goodsTypeId.longValue() == SysConstant.XT_DIC_GOODS_TYPE.GENERAL_CARGO.getId()) {
                    volumeGeneralDetailList.add(detailPojo);
                } else {
                    volumeFreshDetailList.add(detailPojo);
                }
            }
        }

        if (exceptionInfoStr.length() > 0) {
            deleteFile(filePojo);
            throwException(exceptionInfoStr.toString());
        }

        // 下面开始排序
        if (weightGeneralDetailList.size() > 1) {
            //Collections.sort(weightGeneralDetailList);
            boolean result = bCustomerFeightAgreementDetailService.checkSquence(weightFreshDetailList);
            if (!result) {
                deleteFile(filePojo);
                throwException("【重量运价标准】【普货】运价有非连续值存在，请修改!");
            }
        }
        if (weightFreshDetailList.size() > 1) {
            //Collections.sort(weightFreshDetailList);
            boolean result = bCustomerFeightAgreementDetailService.checkSquence(weightFreshDetailList);
            if (!result) {
                deleteFile(filePojo);
                throwException("【重量运价标准】【鲜活】运价有非连续值存在，请修改!");
            }
        }
        if (volumeGeneralDetailList.size() > 1) {
            //Collections.sort(volumeGeneralDetailList);
            boolean result = bCustomerFeightAgreementDetailService.checkSquence(volumeGeneralDetailList);
            if (!result) {
                deleteFile(filePojo);
                throwException("【体积运价标准】【普货】运价有非连续值存在，请修改!");
            }
        }
        if (volumeFreshDetailList.size() > 1) {
            //Collections.sort(volumeFreshDetailList);
            boolean result = bCustomerFeightAgreementDetailService.checkSquence(volumeFreshDetailList);
            if (!result) {
                deleteFile(filePojo);
                throwException("【体积运价标准】【鲜活】运价有非连续值存在，请修改!");
            }
        }

        // 到此全部校验完成，生成统一的集合放到pojo中
        airPojo.getDetailPojos().addAll(weightGeneralDetailList);
        airPojo.getDetailPojos().addAll(weightFreshDetailList);
        airPojo.getDetailPojos().addAll(volumeGeneralDetailList);
        airPojo.getDetailPojos().addAll(volumeFreshDetailList);


        // 正式入库
        return saveExcelObjToDb(airPojo, opType);
    }

    private void deleteFile(XtUploadFilePojo filePojo) throws Exception {
        if(filePojo==null){
            throwException("删除协议运价文件对象失败!");
        }
        xtUploadFileService.deleteFile(filePojo);
    }


    @Transactional(rollbackFor = {Exception.class})
    public int saveExcelObjToDb(BCustomerAirFreightAgreementPojo airPojo, String opType) throws Exception {

        if(airPojo==null){
            throwException("保存航空协议运价对象参数错误!");
        }

        int effectRow = 0;

        if (opType.equals(SysConstant.OPER_ADD)) {
            effectRow = insert(airPojo);
        } else {
            effectRow = updateAirFreightAgreement(airPojo);
        }

        return effectRow;
    }


    /**
     * 根据开单参数检索相应的费率
     *
     * @param param
     * @return
     */
    public AgrementRatePojo loadAirAgrementRatePojo(Map param) {

        if(param==null || param.isEmpty()){
            return null;
        }

        AgrementRatePojo agrementRatePojo = new AgrementRatePojo();
        agrementRatePojo.setWeightRate(DoubleUtil.round2(0D));
        agrementRatePojo.setVolumeRate(DoubleUtil.round2(0D));
        agrementRatePojo.setWeightStandardTicketPrice(DoubleUtil.round2(0D));
        agrementRatePojo.setVolumeStandardTicketPrice(DoubleUtil.round2(0D));

        //{customerId:deliveryCustomerIdValue,
        // airportId:airportIdValue,
        // cityId:destCityIdValue,
        // airlinesId:airlinesIdValue,
        // flightNo:flightNameValue,
        // goodsTypeId:goodsTypeIdValue,
        // chargeableWeight:chargeableWeightValue,
        // volume:volumeValue}

        String customerId = DataTypeUtil.toStringObject(param.get("customerId"));
        String airportId = DataTypeUtil.toStringObject(param.get("airportId"));
        String cityId = DataTypeUtil.toStringObject(param.get("cityId"));
        String airlinesId = DataTypeUtil.toStringObject(param.get("airlinesId"));
        String flightNo = DataTypeUtil.toStringObject(param.get("flightNo"));
        Long goodsTypeId = DataTypeUtil.toLongObject(param.get("goodsTypeId"));
        Double chargeableWeight = DataTypeUtil.toDouble(param.get("chargeableWeight"));
        Double volume = DataTypeUtil.toDouble(param.get("volume"));

        // 1.根据 customerId airportId cityId airlinesId  flightNo 锁定 b_customer_air_freight_agreement表记录
        BCustomerAirFreightAgreementPojo newPojo = new BCustomerAirFreightAgreementPojo();
        newPojo.setCustomerId(customerId);
        newPojo.setAirportId(airportId);
        newPojo.setCityId(cityId);
        newPojo.setAirlinesId(airlinesId);
        newPojo.setFlightNo(flightNo);

        // 这才是真正从数据库中获取的协议运价明细对象
        BCustomerAirFreightAgreementPojo pojo = bCustomerAirFreightAgreementMapper.getAirFreightAgreementPojo(newPojo);

        if (pojo != null) {
            // 根据 id 获取对应的列表对象
            List<BCustomerFeightAgreementDetailPojo> detailPojos = bCustomerFeightAgreementDetailService.getDetailListByAgreementFreightId(pojo.getId());
            // 1.分离出重量与体积标准两个集合
            List<BCustomerFeightAgreementDetailPojo> weightList = new ArrayList<>();
            List<BCustomerFeightAgreementDetailPojo> volumeList = new ArrayList<>();

            for (BCustomerFeightAgreementDetailPojo detailPojo : detailPojos) {
                Long detailPojoStandardTypeId = detailPojo.getStandardTypeId();
                Long detailPojoGoodsTypeId = detailPojo.getGoodsTypeId();
                if (detailPojoStandardTypeId.longValue() == SysConstant.XT_DIC_CUSTOMER_AGREEMENT_FREIGHT_STANDARD.weight.getId()) {
                    if (detailPojoGoodsTypeId.longValue() == goodsTypeId.longValue()) {
                        weightList.add(detailPojo);
                    }
                } else {
                    if (detailPojoGoodsTypeId.longValue() == goodsTypeId.longValue()) {
                        volumeList.add(detailPojo);
                    }
                }
            }

            // 2.排序一下
            if (weightList.size() > 1) {
                ListSortUtil.sort(weightList, new String[]{"agreementFreightId", "standardTypeId"}, new boolean[]{true, true});
            }

            if (volumeList.size() > 1) {
                ListSortUtil.sort(volumeList, new String[]{"agreementFreightId", "standardTypeId"}, new boolean[]{true, true});

            }

            // 3.开始按值进行寻找
            for (int i = 0; i < weightList.size(); i++) {
                BCustomerFeightAgreementDetailPojo weightDetailPojo = weightList.get(i);
                Integer startValue = weightDetailPojo.getStartValue();
                Integer endValue = weightDetailPojo.getEndValue();
                if (chargeableWeight.doubleValue() >= startValue.intValue() && chargeableWeight.doubleValue() < endValue.intValue()) {
                    agrementRatePojo.setWeightRate(DoubleUtil.round2(weightDetailPojo.getPrice()));
                    break;
                }
            }

            for (int i = 0; i < volumeList.size(); i++) {
                BCustomerFeightAgreementDetailPojo volumeDetailPojo = volumeList.get(i);
                Integer startValue = volumeDetailPojo.getStartValue();
                Integer endValue = volumeDetailPojo.getEndValue();
                if (volume.doubleValue() >= startValue.intValue() && volume.doubleValue() < endValue.intValue()) {
                    agrementRatePojo.setVolumeRate(DoubleUtil.round2(volumeDetailPojo.getPrice()));
                    break;
                }
            }

            /**
             * 根据这三个参数获取用户起票价
             * freight_agreement_id
             * standard_type_id
             * goods_type_id
             * ticket_price
             * comment
             */
            /**
             * String freightAgreementId = DataTypeUtil.toStringObject(param.get("freightAgreementId"));
             *                 Long goodsTypeId = DataTypeUtil.toLong(param.get("goodsTypeId"));
             *                 Long standardTypeId = DataTypeUtil.toLong(param.get("standardTypeId"));
             */


            Map<String, Object> ticketPriceQueryMap = new HashMap<>();
            ticketPriceQueryMap.put("freightAgreementId", pojo.getId());
            ticketPriceQueryMap.put("goodsTypeId", goodsTypeId);

            List<BCustomerFreightTicketPricePojo> ticketPricePojoList = bCustomerFreightTicketPriceService.queryNoPageList(ticketPriceQueryMap);

            if (ticketPricePojoList != null && ticketPricePojoList.size() > 0) {
                // 遍历集合，根据类型来设置参数
                for (BCustomerFreightTicketPricePojo ticketPricePojo : ticketPricePojoList) {
                    if (ticketPricePojo.getStandardTypeId().longValue() == SysConstant.XT_DIC_CUSTOMER_AGREEMENT_FREIGHT_STANDARD.weight.getId()
                            && ticketPricePojo.getGoodsTypeId().longValue() == SysConstant.XT_DIC_GOODS_TYPE.GENERAL_CARGO.getId()) {
                        agrementRatePojo.setWeightStandardTicketPrice(ticketPricePojo.getTicketPrice());
                    } else {
                        agrementRatePojo.setVolumeStandardTicketPrice(ticketPricePojo.getTicketPrice());
                    }
                }
            }

        }

        return agrementRatePojo;
    }

    public BCustomerAirFreightAgreementPojo getPojoByUk(Map param) {
        if(param==null || param.isEmpty()){
            return null;
        }
        /**
         * let airWeightUrl = baseUrl + "standardTypeId=" + standardType.weight;
         *             airWeightUrl += "&customerId=" + deliveryCustomerIdValue;
         *             airWeightUrl += "&airportId=" + airportIdValue;
         *             airWeightUrl += "&cityId=" + destCityIdValue;
         *             airWeightUrl += "&airlinesId=" + airlinesIdValue;
         *             airWeightUrl += "&flightNo=" + flightName.getValue();
         */

        String customerId = DataTypeUtil.toStringObject(param.get("customerId"));
        String airportId = DataTypeUtil.toStringObject(param.get("airportId"));
        String cityId = DataTypeUtil.toStringObject(param.get("cityId"));
        String airlinesId = DataTypeUtil.toStringObject(param.get("airlinesId"));
        String flightNo = DataTypeUtil.toStringObject(param.get("flightNo"));

        BCustomerAirFreightAgreementPojo newPojo = new BCustomerAirFreightAgreementPojo();
        newPojo.setCustomerId(customerId);
        newPojo.setAirportId(airportId);
        newPojo.setCityId(cityId);
        newPojo.setAirlinesId(airlinesId);
        newPojo.setFlightNo(flightNo);

        // 这才是真正从数据中获取的对象
        BCustomerAirFreightAgreementPojo pojo = bCustomerAirFreightAgreementMapper.getAirFreightAgreementPojo(newPojo);


        return pojo;
    }
}
